package com.lynn.common.utils;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.RequiresPermission;

/**
 * DESC:
 * TIME:2019-08-06
 */
public class NetUtil {

    private NetUtil() {
    }


    /**
     * 前往网络设置界面
     * 判断手机系统的版本！如果API大于10 就是3.0+
     * 因为3.0以上的版本的设置和3.0以下的设置不一样，调用的方法不同
     */
    @SuppressLint("ObsoleteSdkInt")
    public static void openSetting(Context context) {
        Intent intent = null;
        if (Build.VERSION.SDK_INT > 10) {
            intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
            /*intent = new Intent(Settings.ACTION_SETTINGS);*/
        } else {
            intent = new Intent();
            ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
            intent.setComponent(cm);
            intent.setAction("android.intent.action.VIEW");
        }

        context.startActivity(intent);
    }

    private static ConnectivityManager getConnectivityManager(Context context) {
        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    /**
     * 获取活动网络信息
     */
    @RequiresPermission("android.permission.ACCESS_NETWORK_STATE")
    private static NetworkInfo getActiveNetworkInfo(Context context) {
        ConnectivityManager cm = getConnectivityManager(context);
        if (cm != null) return cm.getActiveNetworkInfo();
        return null;
    }

    /**
     * 判断网络是否连接
     */
//    @RequiresPermission("android.permission.ACCESS_NETWORK_STATE")
    public static boolean isConnected(Context context) {
        @SuppressLint("MissingPermission")
        NetworkInfo info = getActiveNetworkInfo(context);
        return info != null && info.isConnected();
    }








}
